package com.potenza.training.reply.controller;

import com.alibaba.fastjson.JSON;
import com.potenza.training.reply.entity.EsSubjectEntity;
import com.potenza.training.reply.entity.SubjectEntity;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("reply/each")
public class EstwoConroeller {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @PostMapping("/findEs/{page}/{size}")
    public Map findSearchPage(@RequestBody Map map, @PathVariable Integer page,@PathVariable Integer size) throws IOException, ParseException {
        //返回的map集合
        //Map<String,Object> resultMap = new HashMap<>();

        //构建搜索索引
        SearchRequest searchRequest = new SearchRequest("normal-index-subject");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //根据题目模糊查询
        String title_name1 = (String) map.get("titleName");
        if(!StringUtils.isEmpty(title_name1)){
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(title_name1,  "title_name","subiect_desc","key_word_name");
            boolQueryBuilder.must(multiMatchQueryBuilder);
        }
        String list = JSON.toJSONString(map.get("defenseList"));
        List<SubjectEntity> list2 = (List<SubjectEntity>) JSON.parseArray(list,SubjectEntity.class);
        if (!StringUtils.isEmpty(list2)&&list2!=null&&list2.size()!=0){
            for (SubjectEntity subjectEntity : list2) {
                TermQueryBuilder id = QueryBuilders.termQuery("id", subjectEntity.getId());
                boolQueryBuilder.mustNot(id);
            }
        }
        //根据类型模糊查询
        Integer typeId = (Integer) map.get("typeId");
        if(typeId!=null){
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(typeId, "type_id");
            boolQueryBuilder.must(multiMatchQueryBuilder);
        }
        //根据难度模糊查询
        Integer difficltyId = (Integer) map.get("difficltyId");
        if (difficltyId!=null){
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(difficltyId, "difficlty_id");
            boolQueryBuilder.must(multiMatchQueryBuilder);
        }
        searchSourceBuilder.query(boolQueryBuilder);


        //将搜索的数据合并


        //高亮显示（红色加粗)
        HighlightBuilder highlightBuilder= new HighlightBuilder();

        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("title_name");
        highlightBuilder.field("subiect_desc");
        highlightBuilder.field("key_word_name");
        searchSourceBuilder.highlighter(highlightBuilder);
//        HighlightBuilder highlightBuilder2= new HighlightBuilder();
//        highlightBuilder2.preTags("<font color='red'>");
//        highlightBuilder2.postTags("</font>");

//        searchSourceBuilder.highlighter(highlightBuilder2);


        searchSourceBuilder.from((page-1)*size);
        searchSourceBuilder.size(size);
        searchRequest.source(searchSourceBuilder);//2.搜索请求关联 查询对象
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);//1.返回查询结果
        //合并所有的查询条件

        SearchHits hits = searchResponse.getHits();
        //long value = hits.getTotalHits().value;
/*
	private String subjectType;
        private String subjectDifficlty;
        private String titleName;
        private String standardAnswer;
        private Integer timeLimit;
        private String subiectDesc;
        private Integer isStart;
        private Date beginData;
        private Date endData;

 */
        SearchHit[] hits1 = hits.getHits();
        List<EsSubjectEntity> list1=new ArrayList<>();
        for (SearchHit documentFields : hits1) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            EsSubjectEntity subjectEntity = new EsSubjectEntity();
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            subjectEntity.setId(Long.parseLong(sourceAsMap.get("id").toString()));
            subjectEntity.setTitleName((String) sourceAsMap.get("title_name"));
            subjectEntity.setStandardAnswer((String) sourceAsMap.get("standard_answer"));
            subjectEntity.setSubjectType((String) sourceAsMap.get("subject_type"));
            subjectEntity.setSubjectDifficlty((String) sourceAsMap.get("subject_difficlty"));
            subjectEntity.setSubiectDesc((String) sourceAsMap.get("subiect_desc"));
            subjectEntity.setTimeLimit((Integer) sourceAsMap.get("time_limit"));
            subjectEntity.setIsStart((Integer) sourceAsMap.get("is_start"));
            subjectEntity.setDifficltyId((Integer) sourceAsMap.get("difficlty_id"));
            subjectEntity.setTypeId((Integer) sourceAsMap.get("type_id"));
            subjectEntity.setKeyWordName((String) sourceAsMap.get("key_word_name"));
//            String begin_data = (String) sourceAsMap.get("begin_data");
//            Date begin_data_parse = format.parse(begin_data);
//           subjectEntity.setBeginData(begin_data_parse);
//
//            String end_data = (String) sourceAsMap.get("end_data");
//            Date end_data_parse = format.parse(end_data);
//            subjectEntity.setEndData(end_data_parse);

            list1.add(subjectEntity);
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            if(highlightFields!=null){
                HighlightField titleName = highlightFields.get("title_name");
                if(titleName!=null){
                    Text[] fragments = titleName.getFragments();
                    if(fragments!=null){
                        subjectEntity.setTitleName(fragments[0].toString());
                    }

                }
            }

            Map<String, HighlightField> highlightFields2 = documentFields.getHighlightFields();
            if(highlightFields2!=null){
                HighlightField titleName2 = highlightFields2.get("subiect_desc");
                if(titleName2!=null){
                    Text[] fragments2 = titleName2.getFragments();
                    if(fragments2!=null){
                        subjectEntity.setSubiectDesc(fragments2[0].toString());
                    }

                }
            }

            Map<String, HighlightField> highlightFields3 = documentFields.getHighlightFields();
            if(highlightFields3!=null){
                HighlightField titleName3 = highlightFields3.get("key_word_name");
                if(titleName3!=null){
                    Text[] fragments3 = titleName3.getFragments();
                    if(fragments3!=null){
                        subjectEntity.setKeyWordName(fragments3[0].toString());
                    }

                }
            }



        }


        Map map1 = new HashMap<>();
        map1.put("list",list1);
        map1.put("total",hits.getTotalHits().value);

        return  map1;
    }

}
